import numpy as np
import math 


def Griewank(xx):
    """
    Griewank函数python实现
    param:xx：n维向量
    return：函数值
    """
    fsum = 0
    prod = 1
    
    for index in range(len(xx)):
        fsum = fsum + xx[index]*xx[index]/4000
        prod = prod * math.cos(xx[index]/math.sqrt(index+1))

    ans = fsum - prod + 1
    return ans

def dGriewank(xx):
    """
    Griewank导函数python实现
    param:xx：n维向量
    return：导函数值
    """
    temp = []
    pai = 1
    for index in range(len(xx)):
        pai = pai*math.cos(xx[index]/math.sqrt(index+1))
    for index in range(len(xx)):
        b = xx[index]/2000 + math.sin(xx[index]/math.sqrt(index+1))/math.sqrt(index+1) * pai / (math.cos(xx[index]/math.sqrt(index+1)))
        temp.append(b)
    array = np.array(temp)

    return array

if __name__ == "__main__":
    xx = [-87.920619819329359985]
    print(Griewank(xx))
    print(dGriewank(xx))